import { defineStore } from 'pinia'
import { Part } from '@/types/system/device-maintenance/part'
import { useDeviceMaintenanceProjectStore } from './project'
import * as api from '@/api/axios/device-maintenance-client'
import { ref, computed, watch } from 'vue'
import { useDeviceMaintenanceSignalRClientStore } from './signalr-client'

export const useDeviceMaintenancePartHomeStore = defineStore('device-maintenance-part-home', () => {
  const isLoading = ref(false)
  const isNeedLoadParts = ref(true)
  const currentProjectName = ref('')
  const isSelectProjectName = ref(false)
  let oldCurrentProjectName = ''
  const parts = ref<Part[]>([])
  const projectNames = computed(() => {
    const store = useDeviceMaintenanceProjectStore()
    return store.projectNames
  })

  const isConnected = computed(() => {
    // 连接到服务器
    const signalrStore = useDeviceMaintenanceSignalRClientStore()
    return signalrStore.isConnected
  })

  watch(currentProjectName, async (newValue) => {
    if (newValue != oldCurrentProjectName) {
      oldCurrentProjectName = newValue
      if (oldCurrentProjectName == '' || oldCurrentProjectName == null) {
        isSelectProjectName.value = false
      } else {
        isSelectProjectName.value = true
      }
      await updatePartsAsync()
    }
  })

  function openLoading() {
    isLoading.value = true
  }

  function closeLoading() {
    isLoading.value = false
  }

  async function connectServerAsync() {
    // 连接到服务器
    const signalrStore = useDeviceMaintenanceSignalRClientStore()
    try {
      openLoading()
      await signalrStore.connectServerAsync()
    } catch (err) {
      closeLoading()
      console.error(err)
      return false
    }
  }

  // 更新部件
  async function updatePartsAsync() {
    const store = useDeviceMaintenanceProjectStore()
    // 判断是否需要加载项目信息
    if (store.isNeedLoadProjects) {
      openLoading()
      const result = await store.updateProjectsAsync()
      if (!result) {
        closeLoading()
        return false
      }
    }
    const currentProject = store.projects.find(
      (item) => item.projectName == currentProjectName.value
    )
    if (currentProject != null) {
      openLoading()
      const result = await api.getPartsAsync(currentProject.id)
      if (result.isSuccess) {
        closeLoading()
        parts.value = result.result ?? []
        isNeedLoadParts.value = false
        return true
      }
    }
    closeLoading()
    return false
  }

  return {
    isConnected,
    isLoading,
    isNeedLoadParts,
    currentProjectName,
    isSelectProjectName,
    parts,
    projectNames,
    connectServerAsync,
    updatePartsAsync,
    openLoading,
    closeLoading
  }
})
